<template>
  <div class="product-management">
    <div class="header">
      <h2>价格管理</h2>
      <div class="filters">
        <el-input
          v-model="localSearchQuery"
          placeholder="搜索商品..."
          class="search-input"
          clearable
          @input="handleSearch"
          @clear="handleSearchClear"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        <el-select v-model="selectedCategory" placeholder="选择分类" class="category-select" @change="handleCategoryChange">
          <el-option label="全部" value="" />
          <el-option label="新鲜水果" value="新鲜水果类别" />
          <el-option label="绿色蔬菜" value="绿色蔬菜类别" />
          <el-option label="优质肉类" value="优质肉类类别" />
          <el-option label="新鲜海鲜" value="新鲜海鲜类别" />
        </el-select>
      </div>
    </div>

    <el-empty v-if="loading" description="加载中...">
      <el-icon class="is-loading"><Loading /></el-icon>
    </el-empty>

    <el-alert
      v-else-if="error"
      :title="error"
      type="error"
      show-icon
    />

    <div v-else-if="filteredProducts.length === 0" class="no-products">
      <el-empty description="没有找到匹配的商品" />
    </div>

    <div v-else class="products-list">
      <el-card v-for="product in filteredProducts" :key="product.id" class="product-card">
        <template #header>
          <div class="product-header">
            <h3>{{ product.name }}</h3>
            <el-tag :type="getCategoryType(product.category)">
              {{ product.category }}
            </el-tag>
          </div>
        </template>
        
        <div class="product-content">
          <div class="product-info">
            <p class="price">¥{{ product.price }}/{{ product.unit }}</p>
            <p class="cost-price">成本价: ¥{{ product.costPrice }}/{{ product.unit }}</p>
            <p class="supplier">供应商：{{ product.supplier }}</p>
            <p class="description">{{ product.description }}</p>
            <div class="stock-info">
              <el-tag :type="getStockStatusType(product.stock)">
                库存: {{ product.stock }}{{ product.unit }}
              </el-tag>
              <el-tag type="info">
                进货时间: {{ formatDate(product.purchaseDate) }}
              </el-tag>
              <el-tag type="info">
                到期日: {{ formatDate(product.expiryDate) }}
                <span v-if="isExpired(product)" class="expiry-expired">商品已过期</span>
                <span v-else-if="isExpiryWarning(product)" class="expiry-warning">即将到期</span>
              </el-tag>
            </div>
            <el-button @click="openEditDialog(product)">修改价格</el-button>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 修改价格的弹窗 -->
    <el-dialog
      v-model="editDialogVisible"
      title="修改价格"
      width="400px"
    >
      <div class="edit-dialog-content">
        <p>当前价格: ¥{{ selectedProduct?.price }}/{{ selectedProduct?.unit }}</p>
        <p>成本价: ¥{{ selectedProduct?.costPrice }}/{{ selectedProduct?.unit }}</p>
        <el-input v-model="newPrice" placeholder="输入新价格" type="number" />
        <div class="price-controls">
          <el-button @click="decreasePrice">-1</el-button>
          <el-button @click="increasePrice">+1</el-button>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="savePrice">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { Search, Loading } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'
import { getToken } from '@/utils/auth'

// 搜索和过滤
const localSearchQuery = ref('')
const selectedCategory = ref('')
const loading = ref(false)
const error = ref(null)
const products = ref([])
const allProducts = ref([])
const categories = ref([])

// 类别映射
const categoryMap = {
  '新鲜水果类别': 1,
  '绿色蔬菜类别': 2,
  '优质肉类类别': 3,
  '新鲜海鲜类别': 4
}

// 获取类别列表
const fetchCategories = async () => {
  try {
    console.log('开始获取类别列表')
    const response = await axios.get('/api/categories/', {
      headers: {
        'Authorization': `Bearer ${getToken()}`
      }
    })
    console.log('获取类别列表响应:', response)
    
    if (response && Array.isArray(response)) {
      categories.value = response
    } else if (response && response.results && Array.isArray(response.results)) {
      categories.value = response.results
    } else {
      console.warn('类别列表响应格式不正确:', response)
      categories.value = []
    }
  } catch (err) {
    console.error('获取类别列表失败:', err)
    categories.value = []
  }
}

// 获取商品列表
const fetchProducts = async () => {
  loading.value = true
  error.value = null
  try {
    const token = getToken()
    if (!token) {
      ElMessage.warning('请先登录')
      return
    }

    console.log('开始获取商品列表')
    
    // 构建查询参数 - 不使用参数过滤，而是获取所有商品后在前端过滤
    const params = {}
    
    console.log('请求参数:', params)
    
    const response = await axios.get('/api/products/', {
      params,
      headers: {
        'Authorization': `Bearer ${token}`
      }
    })
    
    console.log('获取商品列表响应:', response.data)
    
    if (response.data) {
      let productsData = [];
      
      // 处理不同的响应数据结构
      if (Array.isArray(response.data)) {
        productsData = response.data;
      } else if (response.data.items && Array.isArray(response.data.items)) {
        productsData = response.data.items;
      } else if (response.data.results && Array.isArray(response.data.results)) {
        productsData = response.data.results;
      }
      
      // 处理并规范化每个商品的数据结构
      const normalizedProducts = productsData.map(product => {
        console.log('处理商品:', product);
        
        // 获取库存信息
        let stockQuantity = 0;
        if (product.stock_info && Array.isArray(product.stock_info) && product.stock_info.length > 0) {
          stockQuantity = Number(product.stock_info[0].current_stock) || 0;
        } else if (product.stock !== undefined) {
          stockQuantity = Number(product.stock);
        }
        
        // 处理日期
        let purchaseDate = product.purchase_date || product.purchaseDate || null;
        let expiryDate = product.expiry_date || product.expiryDate || null;
        
        // 处理类别名称，去掉"类别"后缀
        let categoryName = '';
        let categoryId = null;
        
        // 调试输出类别信息
        console.log('商品类别信息:', {
          category: product.category,
          category_id: product.category_id,
          category_detail: product.category_detail
        });
        
        if (product.category_detail) {
          categoryName = product.category_detail.description?.replace(/类别$/, '') || 
                        product.category_detail.name || '未分类';
          categoryId = product.category_detail.id;
        } else if (product.category) {
          categoryName = typeof product.category === 'string' ? 
                        product.category.replace(/类别$/, '') : '未分类';
        }
        
        // 规范化商品数据
        return {
          id: product.id,
          name: product.name || '未命名商品',
          category: categoryName,
          categoryId: categoryId || product.category_id,
          price: Number(product.price) || 0,
          costPrice: Number(product.cost_price || product.costPrice) || 0,
          unit: product.unit || '个',
          supplier: product.supplier || '未知供应商',
          description: product.description || '无描述',
          stock: stockQuantity,
          purchaseDate: purchaseDate,
          expiryDate: expiryDate,
          expiryWarning: Number(product.expiry_warning || product.expiryWarning) || 3,
          // 保留原始数据，以防需要
          originalData: product
        };
      });
      
      // 保存所有产品数据
      allProducts.value = normalizedProducts;
      
      // 根据选择的类别过滤产品
      filterProductsByCategory();
      
      console.log('处理后的商品列表:', products.value);
    } else {
      console.warn('商品列表响应格式不正确:', response)
      products.value = []
      allProducts.value = []
    }
  } catch (err) {
    console.error('获取商品列表失败:', err)
    error.value = '获取商品列表失败: ' + (err.response?.data?.detail || err.message)
    ElMessage.error('获取商品列表失败: ' + (err.response?.data?.detail || err.message))
    products.value = []
    allProducts.value = []
  } finally {
    loading.value = false
  }
}

// 按类别过滤产品
const filterProductsByCategory = () => {
  if (!selectedCategory.value) {
    // 如果没有选择类别，显示所有产品
    products.value = allProducts.value;
    return;
  }
  
  const categoryName = selectedCategory.value.replace(/类别$/, '');
  console.log('过滤类别:', categoryName);
  
  // 根据类别名称过滤
  products.value = allProducts.value.filter(product => {
    const match = product.category === categoryName;
    console.log(`商品 ${product.name} 类别 ${product.category} 匹配 ${categoryName}: ${match}`);
    return match;
  });
  
  console.log(`过滤后的商品数量: ${products.value.length}`);
}

// 处理分类变化
const handleCategoryChange = () => {
  console.log('分类变更为:', selectedCategory.value);
  localSearchQuery.value = ''; // 清空搜索
  filterProductsByCategory(); // 直接过滤现有产品，无需重新获取
}

// 处理搜索
const handleSearch = () => {
  console.log('执行搜索，关键词:', localSearchQuery.value);
  
  // 如果搜索框为空，只按类别过滤
  if (!localSearchQuery.value) {
    filterProductsByCategory();
    return;
  }
  
  // 先获取当前类别过滤后的商品
  let filtered = [...allProducts.value];
  
  // 如果选择了类别，先按类别过滤
  if (selectedCategory.value) {
    const categoryName = selectedCategory.value.replace(/类别$/, '');
    filtered = filtered.filter(product => product.category === categoryName);
    console.log(`按类别 "${categoryName}" 过滤后的商品数量:`, filtered.length);
  }
  
  // 搜索条件：转换为小写并去除首尾空格
  const query = localSearchQuery.value.toLowerCase().trim();
  console.log('处理后的搜索关键词:', query);
  
  // 安全地获取字符串值并转换为小写
  const safeToLowerCase = (value) => {
    if (typeof value === 'string') {
      return value.toLowerCase();
    }
    if (value === null || value === undefined) {
      return '';
    }
    return String(value).toLowerCase();
  };
  
  // 按搜索词过滤，支持多个字段的模糊匹配
  products.value = filtered.filter(product => {
    // 安全地获取所有需要搜索的字段值
    const name = safeToLowerCase(product.name);
    const description = safeToLowerCase(product.description);
    const supplier = safeToLowerCase(product.supplier);
    const category = safeToLowerCase(product.category);
    
    // 记录当前处理的商品信息
    console.log('正在检查商品:', {
      id: product.id,
      name: product.name,
      原始供应商: product.supplier,
      处理后供应商: supplier
    });
    
    // 执行匹配
    const matchName = name.includes(query);
    const matchDescription = description.includes(query);
    const matchSupplier = supplier.includes(query);
    const matchCategory = category.includes(query);
    
    // 记录匹配结果
    console.log(`商品 "${product.name}" 匹配结果:`, {
      名称匹配: matchName,
      描述匹配: matchDescription,
      供应商匹配: matchSupplier,
      类别匹配: matchCategory
    });
    
    return matchName || matchDescription || matchSupplier || matchCategory;
  });
  
  console.log('搜索后的商品数量:', products.value.length);
  
  // 如果没有找到匹配的商品，显示提示
  if (products.value.length === 0) {
    ElMessage.info(`没有找到包含 "${localSearchQuery.value}" 的商品`);
  }
}

// 处理搜索框清空
const handleSearchClear = () => {
  console.log('清空搜索');
  localSearchQuery.value = '';
  filterProductsByCategory(); // 只按类别过滤
}

// 过滤商品列表
const filteredProducts = computed(() => {
  return products.value;
})

// 获取分类样式
const getCategoryType = (category) => {
  const types = {
    '绿色蔬菜': 'success',
    '新鲜水果': 'warning',
    '优质肉类': 'danger',
    '新鲜海鲜': 'info'
  }
  return types[category] || 'info'
}

const getStockStatusType = (stock) => {
  if (stock <= 0) return 'danger'
  if (stock < 100) return 'warning'
  return 'success'
}

const formatDate = (dateString) => {
  if (!dateString) return '未设置';
  try {
    const date = new Date(dateString);
    if (isNaN(date.getTime())) return '日期无效';
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit'
    });
  } catch (error) {
    console.error('日期格式化错误:', error);
    return '日期错误';
  }
}

const isExpiryWarning = (product) => {
  if (!product.expiryDate) return false;
  try {
    const today = new Date();
    const expiryDate = new Date(product.expiryDate);
    if (isNaN(expiryDate.getTime())) return false;
    const diffTime = expiryDate - today;
    const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
    return diffDays > 0 && diffDays <= (product.expiryWarning || 3);
  } catch (error) {
    console.error('到期预警计算错误:', error);
    return false;
  }
}

const isExpired = (product) => {
  if (!product.expiryDate) return false;
  try {
    const today = new Date();
    const expiryDate = new Date(product.expiryDate);
    if (isNaN(expiryDate.getTime())) return false;
    return expiryDate <= today;
  } catch (error) {
    console.error('过期判断错误:', error);
    return false;
  }
}

const editDialogVisible = ref(false)
const selectedProduct = ref(null)
const newPrice = ref(0)

const openEditDialog = (product) => {
  selectedProduct.value = product
  newPrice.value = product.price
  editDialogVisible.value = true
}

const decreasePrice = () => {
  newPrice.value = Math.max(0, newPrice.value - 1)
}

const increasePrice = () => {
  newPrice.value += 1
}

const savePrice = async () => {
  if (selectedProduct.value && newPrice.value >= 0) {
    try {
      console.log('保存新价格:', selectedProduct.value.id, newPrice.value);
      await updateProductPrice(selectedProduct.value.id, newPrice.value)
    editDialogVisible.value = false
    } catch (error) {
      // 错误已在updateProductPrice中处理
    }
  }
}

// 更新商品价格
const updateProductPrice = async (productId, newPrice) => {
  try {
    const token = getToken()
    if (!token) {
      ElMessage.warning('请先登录')
      return
    }

    console.log('开始更新商品价格, ID:', productId, '新价格:', newPrice)
    
    const response = await axios.patch(`/api/products/${productId}/`, {
      price: newPrice
    }, {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    })
    
    console.log('更新商品价格响应:', response.data)
    
    ElMessage.success('价格更新成功')
    await fetchProducts() // 重新获取商品列表以更新数据
  } catch (error) {
    console.error('更新价格失败:', error)
    ElMessage.error('更新价格失败: ' + (error.response?.data?.detail || error.message))
    throw error
  }
}

onMounted(() => {
  fetchCategories()
  fetchProducts()
})

// 调试函数：打印第一个产品的详细结构
const debugProductStructure = (product) => {
  if (!product) return;
  
  console.group('产品数据结构调试');
  console.log('ID:', product.id);
  console.log('名称:', product.name);
  console.log('类别:', product.category);
  console.log('价格:', product.price);
  console.log('成本价:', product.cost_price);
  console.log('单位:', product.unit);
  console.log('供应商:', product.supplier);
  console.log('描述:', product.description);
  
  console.log('库存信息:');
  if (product.stock_info && Array.isArray(product.stock_info)) {
    console.log('  stock_info 数组:', product.stock_info);
    if (product.stock_info.length > 0) {
      console.log('  当前库存:', product.stock_info[0].current_stock);
    }
  } else {
    console.log('  stock 字段:', product.stock);
  }
  
  console.log('日期信息:');
  console.log('  进货日期:', product.purchase_date);
  console.log('  到期日期:', product.expiry_date);
  console.log('  过期预警天数:', product.expiry_warning);
  
  console.log('完整对象:');
  console.dir(product);
  console.groupEnd();
}

// 在获取产品列表后调用调试函数
watch(products, (newProducts) => {
  if (newProducts && newProducts.length > 0) {
    debugProductStructure(newProducts[0].originalData);
  }
}, { immediate: false });

// 监听搜索输入变化，使用防抖处理
let searchTimeout = null;
watch(localSearchQuery, (newVal) => {
  // 清除之前的定时器
  if (searchTimeout) {
    clearTimeout(searchTimeout);
  }
  
  // 设置新的定时器，300ms后执行搜索
  searchTimeout = setTimeout(() => {
    handleSearch();
  }, 300);
});
</script>

<style scoped>
.product-management {
  padding: 20px;
}

.header {
  margin-bottom: 20px;
}

.header h2 {
  margin-bottom: 20px;
  color: #303133;
}

.filters {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}

.search-input {
  width: 300px;
}

.category-select {
  width: 150px;
}

.products-list {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 20px;
  margin-top: 20px;
}

.product-card {
  height: 100%;
  transition: transform 0.3s;
  max-width: 100%;
}

.product-card:hover {
  transform: translateY(-5px);
}

.product-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.product-header h3 {
  margin: 0;
  font-size: 16px;
  color: #303133;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.product-content {
  padding: 10px 0;
}

.product-info {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.product-info .el-button {
  background-color: var(--primary-color);
  color: white;
  border: none;
  transition: background-color 0.3s ease;
}

.product-info .el-button:hover {
  background-color: var(--primary-dark);
  border: none;
}

.price {
  font-size: 18px;
  color: #f56c6c;
  font-weight: bold;
  margin: 0;
}

.cost-price {
  font-size: 14px;
  color: #909399;
  margin: 0;
}

.supplier {
  color: #606266;
  margin: 0;
  font-size: 14px;
}

.description {
  color: #606266;
  margin: 0;
  font-size: 14px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.stock-info {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

/* 到期预警样式 */
.expiry-warning {
  margin-left: 5px;
  background-color: #e6a23c;
  color: white;
  padding: 0 5px;
  border-radius: 3px;
  font-size: 12px;
}

/* 过期标签样式 */
.expiry-expired {
  margin-left: 5px;
  background-color: #f56c6c;
  color: white;
  padding: 0 5px;
  border-radius: 3px;
  font-size: 12px;
}

.edit-dialog-content {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.price-controls {
  display: flex;
  gap: 10px;
}
</style> 